import { Toast } from 'antd-mobile'
import axios, { AxiosError } from 'axios'
import { getTokenInfo, removeTokenInfo, setTokenInfo } from './storage'
import history from './history'
import store from '@/store'
import { saveToken } from '@/store/actions/login'
const baseURL = 'http://geek.itheima.net/v1_0'
const instance = axios.create({
  timeout: 5000,
  baseURL,
})

// 设置拦截器
instance.interceptors.request.use(
  (config) => {
    // 获取token
    const token = getTokenInfo().token
    // 对请求做点什么
    // 设置请求头，对token做统一处理
    config.headers.Authorization = `Bearer ${token}`
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 对响应做点什么
    return response.data
  },
  async (error: AxiosError) => {
    if (!error.response) {
      Toast.show({
        content: '网络繁忙，请稍后重试',
      })
      return Promise.reject(error)
    }
    if (error.response.status !== 401) {
      Toast.show({
        content: error.response.data.message,
      })
      return Promise.reject(error)
    }

    // 判断token 并且拦截
    const { refresh_token } = getTokenInfo()
    if (!refresh_token) {
      // console.log(history);
      // token过期后 没有刷新token，就要拦截
      history.replace({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      return Promise.reject(error)
    }
    // 如果有token并且是401错误
    // 发请求获取新token
    try {
      const res = await axios.put(`${baseURL}/authorizations`, {
        headers: {
          Authorization: 'Bearer ' + refresh_token,
        },
      })
      console.log(res)
      // 将新获取的token保存在redux和本地
      const tokenInfo = {
        token: res.data.data.token,
        refresh_token: refresh_token,
      }
      store.dispatch(saveToken(tokenInfo))
      setTokenInfo(tokenInfo)
      // 重新发送之前那个无效的请求
      instance(error.config)
    } catch (error) {
      // 如果挽救不了，就清除token 然后重新登录
      // 移除本地token
      removeTokenInfo()
      store.dispatch(
        saveToken({
          token: '',
          refresh_token: '',
        })
      )
      // 跳转到登录页
      history.replace({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      return Promise.reject(error)
    }

    return Promise.reject(error)
  }
)

export default instance
